import subprocess
import sys
import re
import time
from datetime import datetime
import threading
import keyboard

# 全局变量，用于控制主循环的运行状态
running = True

def execute_adb_command():
  command = "adb shell COLUMNS=100 top -m 80 -n 1"
  try:
    result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    return result.stdout
  except subprocess.CalledProcessError as e:
    print("执行命令时出错:\n", e.stderr)
    return ""

def grep_output(output, grep_param):
  matched_lines = []
  for line in output.splitlines():
    if re.search(grep_param, line):
      matched_lines.append(line)
  return "\n".join(matched_lines)

def remove_ansi_escape_sequences(text):
  ansi_escape = re.compile(r'\x1b\[([0-9]+)(;[0-9]+)*m')
  return ansi_escape.sub('', text)

def parse_and_sum_output(top_output):
  cpu_sum = 0.0
  res_sum = 0.0
  for line in top_output.splitlines():
    line = remove_ansi_escape_sequences(line).strip()
    columns = line.split()
    if len(columns) >= 9:
      rss = columns[5]
      cpu = columns[8]
      # 处理 RSS 单位
      if rss.endswith('K'):
        rss_value = float(rss[:-1]) / 1024
      elif rss.endswith('M'):
        rss_value = float(rss[:-1])
      elif rss.endswith('G'):
        rss_value = float(rss[:-1]) * 1024
      else:
        rss_value = float(rss)
      # 累加 RSS 和 %CPU 值
      cpu_value = float(cpu)
      res_sum += rss_value
      cpu_sum += cpu_value
  return cpu_sum, res_sum

def check_for_exit():
  global running
  while running:
    if keyboard.is_pressed('q'):
      running = False
      break
    time.sleep(0.1)

if __name__ == "__main__":
  if len(sys.argv) < 2 or len(sys.argv) > 3:
    print("用法: python top_count.py <grep参数> [<CPU阈值>]")
    sys.exit(1)

  grep_param = sys.argv[1]
  cpu_threshold = float(sys.argv[2]) if len(sys.argv) == 3 else 0.0
  cpu_values = []
  res_values = []
  top_outputs = []

  # 生成输出文件名
  current_time = datetime.now().strftime("%y%m%d_%H%M")
  output_filename = f"{grep_param}_{current_time}.log"

  # 启动一个线程来监听退出命令
  exit_thread = threading.Thread(target=check_for_exit)
  exit_thread.daemon = True
  exit_thread.start()

  for i in range(30):
    if not running:
      break
    timestamp = datetime.now().strftime(f"#{i+1:02d} %Y-%m-%d %H:%M:%S")
    output = execute_adb_command()
    if output:
      filtered_output = grep_output(output, grep_param)
      cpu_sum, res_sum = parse_and_sum_output(filtered_output)
      cpu_values.append(cpu_sum)
      res_values.append(res_sum)
      top_outputs.append((timestamp, filtered_output))
      print(f"{timestamp}, %CPU: {cpu_sum:6.1f}%, RES: {res_sum:6.1f} MB")
      print(filtered_output)
    time.sleep(1)  # 等待1秒再执行下一次

  if cpu_values and res_values:
    cpu_min = min(cpu_values)
    cpu_max = max(cpu_values)
    cpu_avg = sum(cpu_values) / len(cpu_values)  # 计算所有值的均值
    cpu_filtered_values = [value for value in cpu_values if value >= cpu_threshold]
    if cpu_filtered_values:
      cpu_avg_threshold = sum(cpu_filtered_values) / len(cpu_filtered_values)
    else:
      cpu_avg_threshold = 0.0
    res_min = min(res_values)
    res_max = max(res_values)
    res_avg = sum(res_values) / len(res_values)

    with open(output_filename, "w", encoding="utf-8") as f:
      f.write(f"{'CPU均值:':<8}{cpu_avg:>6.1f}%\n")
      f.write(f"{'CPU均值:':<8}{cpu_avg_threshold:>6.1f}%{'（阈值 {cpu_threshold}% 以上）'}\n")
      f.write(f"{'CPU最低值:':<8}{cpu_min:>6.1f}%\n")
      f.write(f"{'CPU最高值:':<8}{cpu_max:>6.1f}%\n")
      f.write(f"{'RES均值:':<8}{res_avg:>6.1f} MB\n")
      f.write(f"{'RES最低值:':<8}{res_min:>6.1f} MB\n")
      f.write(f"{'RES最高值:':<8}{res_max:>6.1f} MB\n")
      f.write("\n每次循环的累加值:\n")
      for i in range(len(cpu_values)):
        f.write(f"#{i+1:02d}: %CPU: {cpu_values[i]:6.1f}%, RES: {res_values[i]:6.1f} MB\n")
      f.write("\n每次top输出:\n")
      for timestamp, output in top_outputs:
        f.write(f"{timestamp}\n{output}\n")

    print("每次循环的累加值:")
    for i in range(len(cpu_values)):
      print(f"#{i+1:02d}: %CPU: {cpu_values[i]:6.1f}%, RES: {res_values[i]:6.1f} MB")

    print(f"{'CPU均值:':<8}{cpu_avg:>6.1f}%")
    print(f"{'CPU均值:':<8}{cpu_avg_threshold:>6.1f}%（阈值{cpu_threshold}%以上）")
    print(f"{'CPU最低值:':<8}{cpu_min:>6.1f}%")
    print(f"{'CPU最高值:':<8}{cpu_max:>6.1f}%")
    print(f"{'RES均值:':<8}{res_avg:>6.1f} MB")
    print(f"{'RES最低值:':<8}{res_min:>6.1f} MB")
    print(f"{'RES最高值:':<8}{res_max:>6.1f} MB")